<?php
/**
 * Created by PhpStorm.
 * User: Lee
 * Date: 2020/1/3
 * Time: 9:51
 */
namespace App\Services\Backend\System;

use App\Common\Exception\ErrorException;
use App\Models\Backend\System\Group;
use App\Repositories\Backend\System\UserRepository;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\Backend\System\User;
use App\Models\Backend\System\Role;

/**
 * 系统管理-用户管理 (服务)
 */
class UserService
{
    /** @var UserRepository $userRepository */
    private $userRepository;

    public function __construct()
    {
        $this->userRepository = app('userRepository');
    }

    // 获取列表
    public function getList($requestData){
        $qrySql = "SELECT tb.* ";
        $qrySql .= "FROM vw_user_moreinfo AS tb ";
        $qrySql .= "WHERE tb.is_del='0'";

        // 搜索
        if(isset($requestData['filters']['user_name']) && !empty($requestData['filters']['user_name'])){
            $qrySql .= " AND tb.user_name like '%{$requestData['filters']['user_name']}%'";
        }
        if(isset($requestData['filters']['user_id']) && !empty($requestData['filters']['user_id'])){
            $qrySql .= " AND tb.user_id like '%{$requestData['filters']['user_id']}%'";
        }
        if(isset($requestData['filters']['school']) && !empty($requestData['filters']['school'])){
            $qrySql .= " AND tb.school like '%{$requestData['filters']['school']}%'";
        }
        if(isset($requestData['filters']['gender']) && !empty($requestData['filters']['gender'])){
            $qrySql .= " AND tb.gender = '{$requestData['filters']['gender']}'";
        }
        if(isset($requestData['filters']['active_flag']) && $requestData['filters']['active_flag'] !== ''){
            $qrySql .= " AND tb.active_flag = {$requestData['filters']['active_flag']}";
        }

        if(isset($requestData['filters']['role_id']) && !empty($requestData['filters']['role_id'])){
            $result = DB::table(DB::raw("($qrySql) as users"))->whereRaw('FIND_IN_SET('.$requestData['filters']['role_id'].',role_id)')->orderBy('id','asc')->paginate($requestData['limit'],['*'],'page',$requestData['page']);
        }else{
            $result = DB::table(DB::raw("($qrySql) as users"))->orderBy('id','asc')->paginate($requestData['limit'],['*'],'page',$requestData['page']);
        }

        return $result->toArray();
    }

    public function getTeacherList($requestData){
        $qrySql = "SELECT tb.* ";
        $qrySql .= "FROM vw_user_moreinfo AS tb ";
        $qrySql .= "WHERE tb.is_del='0'";

        // 搜索
        if(isset($requestData['filters']['user_name']) && !empty($requestData['filters']['user_name'])){
            $qrySql .= " AND tb.user_name like '%{$requestData['filters']['user_name']}%'";
        }
        if(isset($requestData['filters']['user_id']) && !empty($requestData['filters']['user_id'])){
            $qrySql .= " AND tb.user_id like '%{$requestData['filters']['user_id']}%'";
        }
        if(isset($requestData['filters']['school']) && !empty($requestData['filters']['school'])){
            $qrySql .= " AND tb.school like '%{$requestData['filters']['school']}%'";
        }
        if(isset($requestData['filters']['school_id']) && !empty($requestData['filters']['school_id'])){
            $qrySql .= " AND tb.group_id = '{$requestData['filters']['school_id']}'";
        }
        $qrySql .= " AND tb.user_type like '1_1__' ";
        $result = DB::table(DB::raw("($qrySql) as users"));
        $ids_arr = [];
        if (isset($requestData['checked_data']) && !empty($requestData['checked_data'])){
            $ids_arr = array_column($requestData['checked_data'],'id');
            $idsStr = implode(',',$ids_arr);
            $result =  $result->orderByRaw("field(id,{$idsStr}) desc");
        }else{
            $result =  $result->orderBy('id','asc');
        }
        $result = $result->paginate($requestData['limit'],['*'],'page',$requestData['page']);
        $rows = $result->toArray();
        if (!empty($ids_arr)){
            foreach ($rows['data'] as &$val) {
                if (in_array($val->id,$ids_arr) !== false){
                    $val->checked = true;
                }else{
                    $val->checked = false;
                }
            }
        }
        return $rows;
    }

    //获取所有角色
    public function getAllRole(){
        $filters = [];
        $filters[] = ['status','=','1'];

        /** @var \App\Services\Backend\System\RoleService $roleService */
        $roleService = app('roleService');

        $result = $roleService->getAll($filters,[],['id','rolename']);

        return $result->toArray();
    }

    //设置用户角色
    public function setUserRole($requestData){
        $id = $requestData['id'];
        /** @var \App\Models\Backend\System\User $user */
        $user = $this->userRepository->get($id);
        if(!$user){
            throw new ErrorException('用户不存在');
        }
        $user->roles()->detach();
        if (is_array($requestData['roleid'])){
            foreach ($requestData['roleid'] as $roleid){
                $user->roles()->attach($roleid);
            }
        }else{
            $user->roles()->attach($requestData['roleid']);
        }

    }

    public function setUserStatus($requestData)
    {
        $id = $requestData['id'];
        $status = '1';
        if($requestData['status'] == '2'){
            $status = '0';
        }
        if (is_array($id)){
            foreach ($id as $v) {
                $this->userRepository->edit(['active_flag' => $status],$v);
            }
        }else{
            $this->userRepository->edit(['active_flag' => $status],$id);
        }


    }

    //判断用户角色
    public function getUserRole($requestData){
        $id = $requestData['id'];
        /** @var \App\Models\Backend\System\User $user */
        $user = $this->userRepository->get($id);
        if(!$user){
            throw new ErrorException('用户不存在');
        }
        $role = $user->roles()->get()->first();
        if (!$role){
            return TEACHER_ROLEID;
        }else{
            return $role->id;
        }

    }

    public function getGroupTree(){
        /** @var \App\Services\Backend\System\GroupService $groupService */
        $groupService = app('groupService');

        $menus = [];
        $school = Auth::user()->school();
        $schoolObject = [
            'id' => $school['id'],
            'title' => $school['group_name'],
            'group_flag' => $school['group_flag'],
            'spread' => true,
            'children' => array(),
        ];
        $menus[$school['id']] = $schoolObject;

        $grades = $groupService->getAllGradeCore($school['id']);
        $grades = $grades->toArray();
        foreach ($grades as $grade){
            $gradeObject = [
                'id' => $grade['id'],
                'title' => $grade['group_name'],
                'group_flag' => $grade['group_flag'],
                'spread' => false,
                'children' => array(),
            ];
            $menus[$school['id']]['children'][$grade['id']] = $gradeObject;

            $classes = $groupService->getAllClassCore($grade['id']);
            $classes = $classes->toArray();
            foreach ($classes as $class){
                $classObject = [
                    'id' => $class['id'],
                    'title' => $class['group_name'],
                    'group_flag' => $class['group_flag']
                ];
                $menus[$school['id']]['children'][$grade['id']]['children'][$class['id']] = $classObject;
            }
        }

        $menus = array_values($menus);
        foreach($menus as $k => $v){
            $menus[$k]['children'] = array_values($menus[$k]['children']);

            foreach($menus[$k]['children'] as $k_g => $v_g){
                $menus[$k]['children'][$k_g]['children'] =  array_values( $menus[$k]['children'][$k_g]['children']);
            }
        }

        return $menus;
    }

    /**
     * 获取用户信息
     * @author lxy
     * @datetime 2021-04-21
     */
    public function getUser()
    {
        $userObj = $this->userRepository->get(auth()->user()->id);
        // $arr = [];
        // $a = '';
        // if($userObj->rj_class){
        //     foreach(json_decode($userObj->rj_class,true) as $k=>$v){
        //         $arr[] = $v['value'];
        //         $a .= $v['name'].',';
        //     }
        //     $userObj->rj_class_s = $arr;
        // }else{
        //     $userObj->rj_class_s = $arr;
        // }
        // $userObj->rj_class_text = rtrim($a,',');

        /** @var TeacherService $teacherService */
        $teacherService = app('teacherService');
        $teacherRows = $teacherService->getAllCore([['teacher_id','=',$userObj->user_uuid]],[]);
        $subjects = [];
        $classnames = [];
        foreach ($teacherRows as $teacherRow) {
            $subjects[] = $teacherRow->subject;
            $classnames[] = $teacherRow->classroom_name;
        }
        $subjects = array_unique($subjects);
        $userObj->subject = implode(',',$subjects) ?? '';
        $userObj->classroom_name = implode(',',$classnames) ?? '';
        $roleRows = DB::table('role_user')->where('user_id','=',auth()->user()->id)->get(['role_id']);
        $rolenames = [];
        foreach ($roleRows as $roleRow) {
            $roleObj = DB::table('roles')->where('id','=',$roleRow->role_id)->first();
            $rolenames[] = $roleObj->rolename;

        }
        $userObj->rolename = implode(',',$rolenames) ?? '';
        return $userObj;
    }

    /**
     * 设置用户信息
     * @author lxy
     * @datetime 2021-04-21
     */
    public function setUser($request)
    {
        $id = $request['id'];
        unset($request['file'],$request['id'],$request['rolename'],$request['classroom_name'],$request['subject']);

        //编辑
        $result = $this->userRepository->edit($request,$id);
        return $result;
    }

    //编辑个人信息
    public function editUserInfo($requestData){
        $user = Auth::user();
        $this->userRepository->edit($requestData, $user->id);
    }

    //*******************外部调用方法****************************************************
    public function getCore($id,$keyName='id',$columns=['*']){
        return $this->userRepository->get($id, $keyName,$columns);
    }

    public function delCore($id,$keyName=false){
        $row = $this->userRepository->get($id, $keyName);
        if ($row){
            return $this->userRepository->delete($id, $keyName);
        }else{
            return true;
        }

    }

    public function editCore($data,$id,$keyName='id'){
        return $this->userRepository->edit($data,$id,$keyName);
    }

    /**
     * 获取用户表中的活动指导老师老师
     * @return array
     */
    public function getTutorsCore()
    {
        $users = DB::table('users')->leftJoin('role_user','users.id','=','role_user.user_id')->where('role_id',ACTIVITYADMIN_ROLEID)->get();
        $returnData = [];

        foreach ($users as $k => $item) {
           $returnData[$k]['name'] = $item->user_name;
           $returnData[$k]['value'] = $item->id;
        }
        return $returnData;
    }

}
